package io.chance.receiverlei.schedule;

import io.chance.receiverlei.db.DataPool;
import io.chance.receiverlei.db.DataPoolManager;
import io.chance.receiverlei.db.DbManager;
import lrq.common.MyLog;
import org.apache.log4j.Logger;

import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class DataInsert extends Thread {
	
	private static Logger log ;
	private int poolSize = 200;
	private int maxWaitSecond = 60 * 5;
	private static ThreadPoolExecutor executorPool;
	
	/**
	 * 
	 */
	public DataInsert() {
		executorPool = (ThreadPoolExecutor)Executors.newFixedThreadPool(50);
	}
	
	@Override
	public void run() {
		
		if(log == null){
			log = MyLog.getLogger(getClass().getSimpleName());
		}
		
		while(true){
			for(Entry<String, List<DataPool>> entry : DataPoolManager.getInstance().getDataPoolsMap().entrySet()){
				
				List<DataPool> dataPools = entry.getValue();
				for(DataPool dataPool:dataPools){
					
					if(dataPool.getModelPoolSize() > poolSize){
						int size = dataPool.getModelPool().size();
						log.info("数量达标,"+dataPool.getId()+","+size);
						executeInsert(dataPool);						
						continue;
					}
					
					if(dataPool.getModelPoolSize() > 0 && dataPool.getNewDataStartTimeDiff() > maxWaitSecond){
						log.info("时间超限,"+dataPool.getId()+","+(dataPool.getNewDataStartTimeDiff()/60));
						executeInsert(dataPool);
						continue;
					}					
				}
			}
			
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				log.error("错误", e);
			}
		}
	}
	
	private void executeInsert(DataPool dataPool){
		
		InsertRun insertRun = new InsertRun(dataPool);
		executorPool.execute(insertRun);
	}
	
	public class InsertRun extends Thread{

		DataPool dataPool;	
		
		public InsertRun(DataPool dataPool) {
			this.dataPool = dataPool;
		}
		
		@Override
		public void run() {
			dataPool.setExecuting(true);
			try {
				DbManager.getDbExecuter().Create(dataPool.getModelPool());
				int size = dataPool.getModelPool().size();
				dataPool.clear();
				log.info("插入成功,"+dataPool.getId()+","+size);
			} catch (Exception e) {
				log.error("插入失败,"+dataPool.getId(), e);
			}
			finally {
				dataPool.clear();
				dataPool.setExecuting(false);
			}
		}
		
	}
	
}
